<?php
	//自动结算一小时扫描数据库一次,超过7天时间自动结算
	file_put_contents("dingshi.txt", date("Y-m-d H:i:s") . "执行定时任务！自动结算" . "\r\n", FILE_APPEND);
	$rs=M('order')->field('order_id,store_id,buyer_id,finnshed_time,order_amount,daiyan_sale,buyer_id,coupon')->where("order_state='40' and refund_state=0 and lock_state=0" )->select();

	foreach($rs as $key=>$value){
		$endtime=$value['finnshed_time']+604800;
		$now=time();
		if($now>$endtime){
			//开启  锁定
			$sssdata['lock_state']=1;
    		M('order')->where("order_id=".$value['order_id'])->save($sssdata);
    		M('order_goods')->where("order_id=".$value['order_id'])->save($sssdata);
			//店铺收入打款入账
    		$youhui_price=get_coupon_price($value['buyer_id'],$value['coupon']);
    		$count_price=$value['order_amount']-$value['daiyan_sale']-$youhui_price;
    		$store_money_log=M('store_money_log')->where("order_id=".$value['order_id'])->select();
    		if($store_money_log==null){
    			if($count_price>0){
	    			$money_rs=M('store')->where("id=".$value['store_id'])->setInc("money",$count_price);
	    			if($money_rs){
		    			$store_log['store_id']=$value['store_id'];
		    			$store_log['addtime']=time();
		    			$store_log['money']=$count_price;
		    			$store_log['type']=1;
		    			$store_log['other']='订单结算收入';
		    			$store_log['order_id']=$value['order_id'];
		    			$store_log['money_type']=1;
		    			M('store_money_log')->add($store_log);
		    		}
	    		}else{

	    			$store_log['store_id']=$value['store_id'];
	    			$store_log['addtime']=time();
	    			$store_log['money']=0;
	    			$store_log['type']=1;
	    			$store_log['other']='该订单免费';
	    			$store_log['order_id']=$value['order_id'];
	    			$store_log['money_type']=1;
	    			M('store_money_log')->add($store_log);

	    		}
    		}
    		//代言打款
			$order_goods_list=M('order_goods')->where("order_id=".$value['order_id']." and recommend_type=0")->select();

			if($order_goods_list){

				foreach($order_goods_list as $k=>$v){
					$user_money_log=M('users_log')->where("order_id=".$value['order_id']." and shop_id=".$v['goods_id'])->select();

					if($v['recommend_id']!=null&&$v['recommend_price']>0&&$user_money_log==null){
						$user_money_rs=M('users')->where("id=".$v['recommend_id'])->setInc("money",$v['recommend_price']);
						if($user_money_rs){
							$user_log['uid']=$v['recommend_id'];
							$user_log['addtime']=time();
							$user_log['money']=$v['recommend_price'];
							$user_log['type']=1;
							$user_log['other']='红包收入';
							$user_log['store_id']=$value['store_id'];
							$user_log['order_id']=$value['order_id'];
							$user_log['shop_id']=$v['goods_id'];
							$user_log['money_type']=2;
							M('users_log')->add($user_log);
						}
					}
				}
			}

		}
	}

?>
